package com.aijk.web.admin.controller.medical;

import com.aijk.commons.lang.utils.StringUtil;
import com.aijk.commons.mijo.utils.PojoUtil;
import com.aijk.commons.utils.Utils;
import com.aijk.medical.api.FdStatisticApi;
import com.aijk.medical.api.MedTeamApi;
import com.aijk.medical.model.vo.MedTeamVo;
import com.aijk.web.admin.RetMsg;
import com.aijk.web.admin.controller.BaseController;
import com.aijk.web.admin.entity.Constant;
import com.aijk.web.admin.model.MedTeamExt;
import com.aijk.web.admin.utils.DataTableUtil;
import com.github.pagehelper.PageInfo;
import com.lifesea.familydoctor.api.FdTeamApi;
import com.lifesea.familydoctor.api.FdTeamAreaApi;
import com.lifesea.familydoctor.model.FdTeam;
import com.lifesea.familydoctor.model.qo.FdServantQo;
import com.aijk.medical.model.ext.FdFdStatisticsMember;
import com.aijk.medical.model.qo.FdStatisticsQo;
import com.lifesea.familydoctor.model.qo.FdTeamAreaQo;
import com.lifesea.familydoctor.model.vo.FdTeamAreaVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Quest on 2017/9/20.
 */
@Controller
@RequestMapping("/medical/team")
public class MedTeamController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(MedTeamController.class);
    @Autowired
    private MedTeamApi medTeamApi;
    @Autowired
    private FdTeamApi fdTeamApi;
    @Autowired
    private FdTeamAreaApi teamAreaApi;
    @Autowired
    private FdStatisticApi statisticApi;

    /**
     * @Description: 进入团队页面
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list_view(String idcard, Model model) {
        HttpSession session = request.getSession();
        session.setMaxInactiveInterval(36000);// 单位：秒

        if(StringUtils.isNotBlank(idcard)){
            //（第一次进入）存医生身份证
            session.setAttribute(Constant.SESSION_IDCARD, idcard);
            if (logger.isInfoEnabled()) {
                logger.info("idcard存入session成功!idcard:{}",idcard);
            }
            model.addAttribute("idcard", idcard);
        }else{
            String sessionIdcard = (String)session.getAttribute(Constant.SESSION_IDCARD);
            if(StringUtils.isNotBlank(sessionIdcard)){
                model.addAttribute("idcard", sessionIdcard);
            }else{
                model.addAttribute("msg", "身份信息已失效，请重新登录！");
                return "/error/error_msg";
            }
        }
        //如果该用户团队只有一条记录，直接跳转“已签页面”
        FdServantQo qo = new FdServantQo();
        qo.setIdcard(idcard);
        PageInfo<MedTeamVo> pageInfo = medTeamApi.pageByServant(qo);
        if(pageInfo.getSize() == 1){
            return switchTeam(pageInfo.getList().get(0).getTeamId(), model);
        }
        //用户“已选择”团队，直接进入"已签页面"
        FdTeam currentTeam = (FdTeam) session.getAttribute(Constant.SESSION_TEAM);
        if(currentTeam != null){
            for(MedTeamVo vo : pageInfo.getList()){
                if(currentTeam.getTeamId().equals(vo.getTeamId())){
                    return switchTeam(currentTeam.getTeamId(), model);
                }
            }
        }
        return "medical/team/list";
    }
    /**
     * @Description: 加载家医所属团队列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public RetMsg list(@RequestParam HashMap skey, @RequestParam(value = "draw", defaultValue = "1") Integer draw) {
        DataTableUtil.FormatOptions(skey);
        if (Utils.isNotEmpty(skey.get("orderbyclause"))) {
            skey.put("orderbyclause", StringUtil.toUnderlineCase(Utils.toString(skey.get("orderbyclause"))));
        }
        FdServantQo qo = DataTableUtil.fillQo(skey,FdServantQo.class);
        if (StringUtils.isBlank(qo.getIdcard())) {
            HttpSession session = request.getSession();
            qo.setIdcard((String) session.getAttribute(Constant.SESSION_IDCARD));
        }
        PageInfo<MedTeamVo> pageInfo = medTeamApi.pageByServant(qo);
        List<MedTeamExt> medTeamExts = new ArrayList<>();
        //判断是否已选择
        /*HttpSession session = request.getSession();
        FdTeam chosenTeam = (FdTeam) session.getAttribute(Constant.SESSION_TEAM);
        Integer chosenTeamId = null;
        if(chosenTeam != null){
            chosenTeamId = chosenTeam.getTeamId();
        }*/
        for (MedTeamVo medTeamVo : pageInfo.getList()) {
            MedTeamExt teamExt = PojoUtil.convert(medTeamVo, MedTeamExt.class);
            FdTeamAreaQo areaQo = new FdTeamAreaQo();
            areaQo.setTeamId(teamExt.getTeamId());
            List<FdTeamAreaVo> teamAreaVoList = teamAreaApi.list(areaQo);
            //服务街道
            StringBuilder streets = new StringBuilder();
            for (FdTeamAreaVo areaVo : teamAreaVoList) {
                streets.append(areaVo.getStreetName()).append(",");
            }
            if(streets.length() > 1)
                teamExt.setStreets(streets.substring(0,streets.length()-1));
            //是否已选择
            /*if(chosenTeamId != null && chosenTeamId.equals(teamExt.getTeamId())){
                teamExt.setHasChosen(true);
            }*/
            //签约统计
            teamExt.setSignCount(calSignCount(teamExt.getTeamId()));
            medTeamExts.add(teamExt);
        }

        RetMsg regMsg = new RetMsg();
        regMsg.put("data", medTeamExts);
        regMsg.put("recordsTotal", pageInfo.getTotal());
        regMsg.put("recordsFiltered", pageInfo.getTotal());
        regMsg.put("draw", draw);

        return regMsg;
    }

    @RequestMapping(value="/list_team", method = RequestMethod.POST)
    @ResponseBody
    public RetMsg list_team(String idcard){
        FdServantQo qo = new FdServantQo();
        if(StringUtils.isNotBlank(idcard) && !"undefind".equals(idcard)){
            qo.setIdcard(idcard);
        }else{
            HttpSession session = request.getSession();
            qo.setIdcard((String) session.getAttribute(Constant.SESSION_IDCARD));
        }
        PageInfo<MedTeamVo> pageInfo = medTeamApi.pageByServant(qo);
        RetMsg retMsg = new RetMsg();
        retMsg.put("data", pageInfo.getList());
        return retMsg;
    }

    /**
     *@Description: 切换团队
     */
    @RequestMapping(value = "/switch", method = RequestMethod.GET)
    public String switchTeam(@RequestParam Integer id, Model model) {
        try {
            //团队信息
            FdTeam teamInfo = fdTeamApi.find(id);
            if(teamInfo != null){
                //存team对象
                HttpSession session = request.getSession();
                session.setMaxInactiveInterval(36000);// 单位：秒
                session.setAttribute(Constant.SESSION_TEAM,teamInfo);
                if (logger.isInfoEnabled()) {
                    logger.info("团队信息存入session成功!teamId:{},teamName:{}",id,teamInfo.getTeamName());
                }
            }else{
                model.addAttribute("msg","未查询到该团队信息");
                return "/error/error_msg";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return redirect("/medical/sign/list");//跳转“已签”页面
    }

    /**
     *@Description: 计算签约数量
     */
    private int calSignCount(Integer teamId){
        FdStatisticsQo qo = new FdStatisticsQo();
        qo.setTeamId(teamId);
        PageInfo<FdFdStatisticsMember> pageInfo = statisticApi.statisticsMember(qo);
        int signNumTotal = 0;
        for (FdFdStatisticsMember item: pageInfo.getList()) {
            signNumTotal += (item.getSignNum() == null ? 0 : item.getSignNum());
        }
        //失效服务者的签约数量
        int signNum = statisticApi.countSignWithoutServant(teamId);
        return signNumTotal + signNum;
    }
}
